import { Component, OnInit } from '@angular/core';
import { ItemData } from './ItemData';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { OutputDesignDtoService } from './outputdesigndto.service';
import { saveAs } from 'file-saver'


@Component({
  selector: 'app-outputdesigndto',
  templateUrl: './outputdesigndto.component.html',
  styleUrls: ['./outputdesigndto.component.css']
})

export class OutputdesigndtoComponent implements OnInit {

  constructor(
    private service: OutputDesignDtoService
  ) {}


//   public tab3: string[] = ['10%', '50%'];
  editCache: { [key: string]: { edit: boolean; data: ItemData } } = {};
  listOfData: ItemData[] = [];
  i = 1;
  selectedValue = null;
  filterValue = null;
  classNm = null;
  classCd = null;
  screenIdList: string[] = [];

  startEdit(id: string): void {
    this.editCache[id].edit = true;
  }

  cancelEdit(id: string): void {
    const index = this.listOfData.findIndex(item => item.id === id);
    this.editCache[id] = {
      data: { ...this.listOfData[index] },
      edit: false
    };
  }

  saveEdit(id: string): void {
    const index = this.listOfData.findIndex(item => item.id === id);
    Object.assign(this.listOfData[index], this.editCache[id].data);
    this.editCache[id].edit = false;
  }

  updateEditCache(): void {
    this.listOfData.forEach(item => {
      this.editCache[item.id] = {
        edit: false,
        data: { ...item }
      };
    });
  }
 
  addRow(id: string): void {
	// const index = this.listOfData.findIndex(item => item.id === id);
	// this.listOfData.splice(index, 0, {
    //     id: id+`${this.i}`,
	// 	itemId: `ABC ${this.i}`,
	// 	itemName: `項目名 ${this.i}`,
	// 	itemType: `String`,
	// 	itemGroup: `グループ ${this.i}`,
	// 	itemExplanation: `説明 ${this.i}`
	//   });

    this.listOfData = [
      ...this.listOfData,
      {
        id: id+`${this.i}`,
		itemId: ``,
		itemName: ``,
		itemType: ``,
		structure: ``,
		itemExplanation: ``
      }
    ];

	  this.editCache[id+`${this.i}`] = {
        edit: false,
        data: { 
			id: id+`${this.i}`,
			itemId: ``,
			itemName: ``,
			itemType: ``,
			structure: ``,
			itemExplanation: ``
		 }
      };

	  this.i++;
  }

  deleteRow(id: string): void {
    this.listOfData = this.listOfData.filter(d => d.id !== id);
  }

  ngOnInit(): void {

	const data = [];

    //   data.push({
    //     id: ``,
    //     itemId: ``,
		// itemName: ``,
		// itemType: ``,
		// structure: ``,
    //     itemExplanation: ``
    //   });

    this.listOfData = data;
    this.updateEditCache();

    this.service.getScreenIdList().subscribe(
      data => {this.screenIdList = data;
        if(this.screenIdList.length === 0){
          return;
        }
      }
    );
  }

  onSearch(): void {

    let screenId = this.selectedValue;
    let filterValue = this.filterValue;

    this.service.getDesignScreenDtoList(screenId, filterValue).subscribe(
      data => {this.listOfData = data; 
        if(this.listOfData.length === 0){
          return;
        }
        this.updateEditCache();
      }
    );
  }

  onRegister(): void {

    let outputDesignDtoData:OutputDesignDtoData  = {

      classNm: this.classNm,
      classCd: this.classCd,
      listOfData: this.listOfData
    }
    let screenId = this.selectedValue;
    let filterValue = this.filterValue;

    this.service.register(outputDesignDtoData,screenId,filterValue).subscribe(data => {
      const link = document.createElement('a');
      const blob = new Blob([data.body], { type: 'application/vnd.ms-excel' });
      link.setAttribute('href', window.URL.createObjectURL(blob));
      link.setAttribute('download', 'ATCC_DTO仕様書_' + this.classNm + '_' + new Date().getTime() + '.xls');
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      alert("登録しました。");
    });
  }




  // onRegister(): void {

  //   let outputDesignDtoData:OutputDesignDtoData  = {

  //     classNm: this.classNm,
  //     classCd: this.classCd,
  //     listOfData: this.listOfData
  //   }
  //   // let thefile = {};
  //   this.service.exportExcel();
  //   // .subscribe(
  //   //   response => {

  //   //         let blob = new Blob([response], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
  //   //         saveAs(blob, 'test.xlsx');
  //   //       });
  //     }

}
// interface ItemData {
// 	id: string;
// 	itemId: string;
// 	itemName: string;
// 	itemType: string;
// 	itemGroup: string;
// 	itemExplanation: string;
//   }

// interface ItemData {
// 	id: string;
// 	name: string;
// 	age: number;
// 	address: string;
//   }



 interface OutputDesignDtoData {
  classNm: string;
  classCd: string;
  listOfData: ItemData[];
}
